#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>

#include <unistd.h>

#define THRNUM  4
#define FNAME   "/tmp/out"
#define LINSIZE 1024

static pthread_mutex_t mutex[THRNUM];

int next(int n)
{
    if (n + 1 == THRNUM)
        return 0;
    return n + 1;
}

static void *thr_func(void *p)
{
    int n = (int)p;
    int c = 'a' + n;
    while (1)
    {
        pthread_mutex_lock(mutex + n);
        write(1, &c, 1);
        pthread_mutex_unlock(mutex + next(n));
    }
    pthread_exit(NULL);
}

int main()
{
    pthread_t tid[THRNUM];

    for (int i = 0; i < THRNUM; i++)
    {
        pthread_mutex_init(mutex + i, NULL);
        pthread_mutex_lock(mutex + i);
        pthread_create(tid + i, NULL,thr_func, (void *)(i));   
    }
    pthread_mutex_unlock(mutex + 0);

    alarm(5);

    for (int i = 0; i < THRNUM; i++)
    {
        pthread_join(tid[i], NULL);
    }
    exit(0);
}